﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uREST.Core.Handlers;
using uREST.Core.Attributes;
using OpenRasta.Web;
using umbraco.cms.businesslogic.web;
using uREST.Blog.Extensions;
using uREST.CMS.Extensions;
using uREST.CMS.Util;

namespace uREST.Blog.Handlers
{
    [UmbracoAuthorize(Applications = "content")]
    public class BlogHandler : AbstractHandler
    {
        public const string DOC_TYPE_ALIAS = "Blog";

        public BlogHandler(ICommunicationContext context)
            : base(context)
        { }

        // GET (LIST)
        [HttpOperation(ForUriName = "BlogList")]
        public OperationResult GetBlogList()
        {
            var blogDocs = UmbracoHelper.GetDocumentsByDocTypeAlias(BlogHandler.DOC_TYPE_ALIAS, AuthenticatedUser);

            return new OperationResult.OK { ResponseResource = blogDocs.ToBlogResourceList() };
        }

        // GET (SINGLE)
        [HttpOperation(ForUriName = "Blog")]
        public OperationResult GetBlog(
            int id)
        {
            Document doc = null;

            try
            {
                doc = new Document(id);
            }
            catch
            { }

            if (doc == null)
                return new OperationResult.NotFound();

            if (!AuthenticatedUser.CanAccess(doc))
                return new OperationResult.Forbidden();

            var blogDocType = DocumentType.GetByAlias(BlogHandler.DOC_TYPE_ALIAS);
            if (blogDocType == null || blogDocType.Alias != doc.ContentType.Alias)
                return new OperationResult.NotFound();

            return new OperationResult.OK { ResponseResource = doc.ToBlogResource() };
        }
    }
}
